package com.friend.joey.applicationfriend.Classes;

import com.friend.joey.applicationfriend.Classes.Article;
import com.friend.joey.applicationfriend.Classes.Result;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;

import static android.media.CamcorderProfile.get;

/**
 * Created by Joey on 2017/5/28.
 */

public class MyBaiduSearch {
    private static String URL = "http://www.baidu.com/s?pn=%d&wd=%s";
    private static String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36";
    private int pagenumber = 0;//0, 10 ,20 ...固定
    protected String query;
    //测试
    private String a="";//
    private int sa=0;//
    //检索结果
    protected ArrayList<Article> articles = new ArrayList<Article>();
    //中间结果
    protected ArrayList<Result> results;
    //protected ArrayList<Result> results = new  ArrayList<Result>();
    protected ArrayList<Result> partResults=new ArrayList<Result>();
    //单词检索条数(至少)
    protected int min = 10;//20
    //已检索条数
    protected int amount = 0;//单次
    protected int total;//全部
    //接口与抽象类的不同之一:接口没有任何方法
    public MyBaiduSearch(String keyword){
        this.query = keyword;
    }
    public MyBaiduSearch(String keyword,ArrayList<Result> results){
        this.query = keyword;
        this.results=results;
        //this.results=new  ArrayList<Result>();
    }
    public MyBaiduSearch(String keyword, int amount){
        this.query = keyword;
        this.amount = amount;
    }
    //是否满足
    private  boolean isFull () {
        return amount>min;
    }
    private void clearAll(){
        partResults.clear();
    }
    public void search() throws Exception {
        String url = String.format(URL, pagenumber, query);
        Document doc = null;
        doc = Jsoup.connect(url).userAgent(userAgent).get();
        Elements baiduResults = doc.getElementsByClass("c-container");
        for (Element result : baiduResults) {
            try  {
                sa++;
                String title = Jsoup.parse(result.getElementsByClass("t").first().select("a[href]").html()).text();
                String href = result.getElementsByClass("t").select("a[href]").attr("href");

                Element e_snippet = result.getElementsByClass("c-abstract").first();
                e_snippet.getElementsByClass("newTimeFactor_before_abs").remove();
                //去掉 百度知道 更多XX问题
                e_snippet.getElementsByTag("a").remove();
                String snippet = Jsoup.parse(e_snippet.html()).text();
                Result tmp = new Result(title, snippet, href);
                //Result tmp = new Result("1", "2 ", "3");
                //logger.info("\n title: {}\n snippet:{}\n href:{}",title,snippet, href);
                partResults.add(tmp);
                results.add(tmp);
            } catch (NullPointerException e) {
                //logger.info("解析错误");
            }
        }
        a+=Integer.toString(sa)+",";
        sa=0;
        amount = partResults.size();
        total+=amount;
        pagenumber += 10;
        return;
    }

    /*
     * 根据简单检索结果,完善为完整结果(根据url获取更多信息)
     */
    public void resultParse() {
        //TODO 涉及到网页去噪的问题,暂时直接返回简单检索结果
        for (int i = 0; i < results.size(); i += 1) {
            articles.add(new Article(-1, results.get(i).getTitle(),results.get(i).getSnippet()));
        }
    }
    public void run() {
        amount=0;
        clearAll();
        while (!isFull()) {
            try {
                search();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    //get
    public ArrayList<Article> getArticles() {
        return articles;
    }
    public ArrayList<Result> getResults(){
        return results;
    }
    public ArrayList<Result> getPartResults(){
        return partResults;
    }
    public int getTotal(){
        return results.size();
    }
    public String getResultString(){
        String string="{results:";
        string+=Integer.toString(results.size())+" "+Integer.toString(pagenumber)+" "+Integer.toString(amount);
//        for (int i = 0; i < results.size(); i += 1) {
//            string+=results.get(i).getString();
//        }
        for (int i = 0; i < amount; i += 1) {
            string+=partResults.get(i).getString();
        }
        return string+"}"+a;
    }
}
